//
//  QBVCImage.m
//  QiuBai
//
//  Created by yaohongchao on 16/4/17.
//  Copyright © 2016年 yaohongchao. All rights reserved.
//

#import "QBVCImage.h"
#import "QBImageCell.h"
#import "QBWordModel.h"
#import "MJRefresh.h"

@interface QBVCImage ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,weak)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *arraySection;
@property(nonatomic,assign)NSInteger page;
@end

@implementation QBVCImage

- (void)viewDidLoad {
    [super viewDidLoad];
    //    [self setupData];
    [self setui];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)setui{
    UITableView *tableView = [[UITableView alloc]init];
    [tableView registerClass:[QBImageCell class] forCellReuseIdentifier:ReuseIdentifierOne];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    tableView.dk_backgroundColorPicker = DKColorPickerWithKey(BG);
    WS(weakSelf);
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
        weakSelf.page = 0;
        [weakSelf.arraySection removeAllObjects];
        [weakSelf setupData];
    }];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    self.navigationController.navigationBar.dk_barTintColorPicker = DKColorPickerWithKey(CellSelectedBg);
    //初始化刷新一次
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        path = [path stringByAppendingPathComponent:@"image.data"];
        self.arraySection = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
        dispatch_async(dispatch_get_main_queue(), ^{
            if(self.arraySection.count > 0){
                [self.tableView reloadData];
            }else{
                [tableView.mj_header beginRefreshing];
            }
        });
    });
}

-(void)setupData{
    
    WS(weakSelf);
    if(!self.arraySection){
        self.arraySection = [NSMutableArray array];
    }
    self.page++;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    ((AFHTTPResponseSerializer *)manager.responseSerializer).acceptableContentTypes = [NSSet setWithObjects:@"text/html", @"application/octet-stream", @"text/xml", nil];
    NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://m2.qiushibaike.com/article/list/imgrank?count=30&page=%ld",(long)self.page]];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
        if (error) {
            NSLog(@"Error: %@", error);
        } else {
            QBWordModel *result = [QBWordModel mj_objectWithKeyValues:responseObject];
            [weakSelf.arraySection addObject:result];
            [weakSelf.tableView reloadData];
            [weakSelf saveData];
        }
        if(weakSelf.arraySection.count > 0 && !weakSelf.tableView.mj_footer){
            weakSelf.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                // 进入刷新状态后会自动调用这个block
                [weakSelf setupData];
            }];
        }
        [weakSelf.tableView.mj_footer endRefreshing];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    [dataTask resume];
}

#pragma mark UITableViewDelegate,UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.arraySection.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return ((QBWordModel*)[self.arraySection objectWithIndex:section]).items.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QBImageCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifierOne];
    QBWordModel *model = [self.arraySection objectWithIndex:indexPath.section];
    cell.item = [model.items objectAtIndex:indexPath.row];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    QBWordModel *model = [self.arraySection objectWithIndex:indexPath.section];
    Item *item = [model.items objectAtIndex:indexPath.row];
    if(item.cellHeight <= 0){
        CGSize size=[item.content boundingRectWithSize:CGSizeMake(SCREEN_WIDTH-2*kMargin, CGFLOAT_MAX)
                                               options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                            attributes:@{NSFontAttributeName: fontContentCell} context:nil].size;
        CGFloat width = SCREEN_WIDTH-2*kMargin;
        CGFloat imageWidth = [item.image_size.m floatWithIndex:0];
        CGFloat imageHeight = [item.image_size.m floatWithIndex:1];
        CGFloat height = imageHeight/imageWidth*width;
        CGFloat cellHeight = height+155+size.height+3*kMargin;
        item.cellHeight = cellHeight;
        item.imageHeight = height;
    }
    return item.cellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)saveData{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        path = [path stringByAppendingPathComponent:@"image.data"];
        [NSKeyedArchiver archiveRootObject:self.arraySection toFile:path];
    });
}

-(void)dealloc{
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    self.tableView = nil;
        
    [self.arraySection removeAllObjects];
    self.arraySection = nil;
}

@end
